package org.geektimes.projects.user.web.controller;

import org.eclipse.microprofile.config.Config;
import org.geektimes.comtext.ClassicComponentContext;
import org.geektimes.projects.user.domain.User;
import org.geektimes.projects.user.service.UserService;
import org.geektimes.web.mvc.controller.PageController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;

import static org.geektimes.utils.ThreadLocalData.threadLocalConfig;

@Path("/register")
public class UserRegisterController implements PageController {

    /**
     * @param request  HTTP 请求
     * @param response HTTP 相应
     * @return 视图地址路径
     * @throws Throwable 异常发生时
     */
    @Override
    @GET
    @Path("")
    public String execute(HttpServletRequest request, HttpServletResponse response) throws Throwable {
        final Config config = threadLocalConfig.get();
        final String hello = config.getValue("hello", String.class);
        request.setAttribute("hello",hello);
        return "register.jsp";
    }

    //注册用户

    @POST
    @Path("/doRegister")
    public String doRegister(HttpServletRequest request, HttpServletResponse response) throws Throwable {
        final String name = request.getParameter("name");
        final String phoneNumber = request.getParameter("phoneNumber");
        final String email = request.getParameter("email");
        final String password = request.getParameter("password");

        User user = new User();
        user.setName(name);
        user.setPhoneNumber(phoneNumber);
        user.setEmail(email);
        user.setPassword(password);

        final ClassicComponentContext context = ClassicComponentContext.getInstance();
        //依赖查找
        UserService userService = context.getComponent("bean/UserService");

        userService.register(user);

        return "success.jsp";
    }

}
